package org.inasnet.user;

import org.inasnet.*;

import java.io.File;

import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class ContactList 
{
	void add( ContactGroup contactGroup )
	{
		mGroups.add( contactGroup );
	}
	
	public List< ContactGroup > getGroupsList()
	{
		return mGroups;
	}
		
	/**
	 * Reads all user contacts from xml file `contact-list.xml`.
	 */
	void restoreFromConfig( String accoundId )
	{
		try 
		{
			  File file = new File( "config/users/" + accoundId + "/contact-list.xml" );
			  
			  Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( file );
			  doc.getDocumentElement().normalize();
			  
			  NodeList groupsList = doc.getDocumentElement().getElementsByTagName( "group" );
			  
			  for( int groupIter = 0; groupIter < groupsList.getLength(); groupIter++ ) 
			  {
				  Element groupElement = ( Element ) groupsList.item( groupIter );
				  
				  NodeList usersList = groupElement.getElementsByTagName( "contact" );
				  
				  ContactGroup contactGroup = new ContactGroup( groupElement.getAttribute( "name" ) );
				  
				  for( int userIter = 0; userIter < usersList.getLength(); userIter++ ) 
				  {
					  Element clientElement = ( Element ) usersList.item( userIter );
					  
					  User user = new User();
					  
					  try 
					  {
						  user.setId( Integer.parseInt( clientElement.getAttribute( "id" ) ) );
					  }
					  catch( Exception e )
					  {
						  e.printStackTrace();
					  }
					  
					  contactGroup.add( user );
				  }
				  
				  add( contactGroup );
			  }		  
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}

	List< ContactGroup > mGroups = new LinkedList< ContactGroup >();
}
